import { ref, useTemplateRef } from 'vue';
import { Account, LoginOptions } from '~/pages/login/type.ts';
import { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '~/store/modules/user.ts';
import { digestByMD5 } from '~/utils';
import { parseAjaxResponse } from '~/common/request.ts';
import { defaultHomePagePath } from '~/router/menu';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

export const useLoginOptions = (formKey: string): LoginOptions => {
  const { t: $t } = useI18n();

  const accountRef = ref<Account>({
    account: '',
    password: ''
  });

  const isLanding = ref(false);

  const accountRules = ref<FormRules<Account>>({
    account: [{ required: true, message: $t('login.rules.account.required'), trigger: 'blur' }],
    password: [{ required: true, message: $t('login.rules.password.required'), trigger: 'blur' }]
  });

  const loginFormRef = useTemplateRef<FormInstance>(formKey);
  const router = useRouter();

  const doLogin = () => {
    loginFormRef.value?.validate(isValid => {
      if (isValid) {
        const user = useUserStore();
        isLanding.value = true;
        let password = digestByMD5(accountRef.value.password);
        user
          .login(accountRef.value.account, password)
          .then(data => {
            isLanding.value = false;
            parseAjaxResponse({
              data,
              onSuccess() {
                router.push({
                  path: defaultHomePagePath
                });
              },
              showErrorMessage: false
            });
          })
          .catch(() => {
            isLanding.value = false;
          });
      }
    });
  };

  return {
    accountRef,
    accountRules,
    isLanding,
    doLogin
  };
};
